<?php
declare (strict_types = 1);
namespace vinchan\encryption\Factory;

use vinchan\encryption\Kernel\FactoryInterface;

class RSA implements FactoryInterface
{
    /**
     * [默认加密模式]
     * @var string
     * openssl_private_encrypt
     * openssl_public_encrypt
     */
    public $defaultEncrypt = 'openssl_private_encrypt';

    /**
     * [默认解密模式]
     * @var string
     * openssl_public_decrypt
     * openssl_private_decrypt
     */
    public $defaultDecrypt = 'openssl_public_decrypt';

    /**
     * [偏移量]
     * OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.
     * @var string
     */
    public $padding = OPENSSL_PKCS1_PADDING;

    public function __construct(array $config = [])
    {
        // 配置默认加密方式
        if (isset($config['defaultEncrypt'])) {
            $this->defaultEncrypt = $config['defaultEncrypt'];
        }
        // 配置默认解密方式
        if (isset($config['defaultDecrypt'])) {
            $this->defaultDecrypt = $config['defaultDecrypt'];
        }
    }

    /**
     * [加密]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function encrypt($data): string
    {
        $method = $this->defaultEncrypt;

        $method($data, $result, $this->key, $this->padding);

        return empty($result) ? "" : $result;
    }

    /**
     * [解密]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function decrypt($data): string
    {
        $method = $this->defaultDecrypt;

        $method($data, $result, $this->key, $this->padding);

        return empty($result) ? "" : $result;
    }

    /**
     * [配置KEY]
     * @return [type] [description]
     */
    public function key($key)
    {
        $this->key = $key;
        return $this;
    }

    /**
     * [设置加密方式]
     * @param  string $str [description]
     * @return [type]      [description]
     */
    public function defaultEncrypt(string $str = "openssl_private_encrypt")
    {
        $this->defaultEncrypt = $str;

        // 公钥函数
        if ($str == 'public') {
            $this->defaultEncrypt = "openssl_public_encrypt";
        }
        // 私钥函数
        if ($str == 'private') {
            $this->defaultEncrypt = "openssl_private_encrypt";
        }

        return $this;
    }

    /**
     * [设置解密方式]
     * @param  string $str [description]
     * @return [type]      [description]
     */
    public function defaultDecrypt(string $str = 'openssl_public_decrypt')
    {
        $this->defaultDecrypt = $str;

        // 公钥解密函数
        if ($str == 'public') {
            $this->defaultDecrypt = "openssl_public_decrypt";
        }

        // 私钥解密函数
        if ($str == 'private') {
            $this->defaultDecrypt = "openssl_private_decrypt";
        }
        return $this;
    }

}
